package control;

import entity.Category;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import utils.ServletUtil;

@WebServlet(name="EditCategory", urlPatterns={"/backend/EditCategory"})
public class EditCategory extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        boolean formSucces = false;
        
        EntityManagerFactory fact = Persistence.createEntityManagerFactory("vh11i_jeePU");
        EntityManager em = fact.createEntityManager();
        
        try {
            // Zoek de categorie via id (staat in de querystring)
            long categoryId = ServletUtil.getLong(request.getParameter("category_id"), -1);
            Category category = em.find(Category.class, categoryId);
            request.setAttribute("category", category);
            
            if (category != null && request.getMethod().equals("POST")) {
                
                category.setName(request.getParameter("name"));
                
                if (category.getName().length() > 0) {
                    em.getTransaction().begin();
                    em.persist(category);
                    em.getTransaction().commit();
                    formSucces = true;
                }
            }
        }
        finally {
            em.close();
            fact.close();
        }
        
        if (formSucces) {
            response.sendRedirect("EditCategory?success=true");
        }
        else {
            RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/editCategory.jsp");
            dispatcher.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
